package com.yeyaomai.dksns.flowis.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Order;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
import com.yeyaomai.dksns.flowis.dao.LoginSessionDao;
import com.yeyaomai.dksns.flowis.domain.flowisdetail.FlowisQueryOrder;
import com.yeyaomai.dksns.flowis.domain.flowisdetail.LoginProfile;
import com.yeyaomai.dksns.flowis.domain.flowisdetail.LoginSession;
import com.yeyaomai.dksns.flowis.page.PageImplResult;
import com.yeyaomai.dksns.flowis.page.PageRequestOrder;
import com.yeyaomai.dksns.flowis.util.ListPropertyAndValueTool;

@Component
public class LoginSessionDaoImpl implements LoginSessionDao {

	@Resource
	protected MongoTemplate mongoPathTemplate;

	@Override
	public Page<LoginSession> getSplit(FlowisQueryOrder order) {

		Query query = new Query();

		for (Map.Entry<String, String> entry : order.getSort().entrySet()) {
			query.sort().on(entry.getKey(), Order.valueOf(entry.getValue()));
		}
		 List<String> includeFields = new ArrayList<String>();
				 includeFields.add("username");
				 includeFields.add("user_dkcode");
				 ListPropertyAndValueTool.querySaveCriteria(query,
				 order,LoginSession.class, includeFields);
		PageRequestOrder request = new PageRequestOrder(Integer.parseInt(order
				.getNumber()), order.getPageSize());
		//query.addCriteria(Criteria.where("username").ne(null));
		long totalSize = getTotalSize(query, LoginSession.class);

		query.skip(request.start()).limit(order.getPageSize());

		List<LoginSession> ps = mongoPathTemplate.find(query,
				LoginSession.class);

		Page<LoginSession> result = new PageImplResult<LoginSession>(ps,
				request, totalSize);
		return result;
	}

	@Override
	public long getTotalSize(Query query, Class<LoginSession> document) {

		return mongoPathTemplate.count(query, document);
	}
	
	@Override
	public Integer getLoginProfileBydkcode(String dkcode) {
		Query query = new Query();
		query.addCriteria(Criteria.where("user_dkcode").is(dkcode));
		List<LoginProfile> list = new ArrayList<LoginProfile>();
		list = mongoPathTemplate.find(query, LoginProfile.class);
		Integer number = 0;
		for (int i = 0; i < list.size(); i++) {
			number += list.get(i).getDistance();
		}
		return number;
	}
}
